<template>
  <view>
    <view class="search-box">
      <uni-search-bar @confirm="search" :radius="100" cancelButton="none" :focus="true" @input="input">
      </uni-search-bar>
    </view>

    <!-- 搜索建议列表; -->
    <view class="sugg-list" v-if="searchResult.length!==0">
      <view class="sugg-item" v-for="(item,index) in searchResult" @click="gotoDetail(item)">
        <view class="goods-name"> {{item.goods_name}}</view>
        <uni-icons type="right" size="16"></uni-icons>
      </view>
    </view>

    <!-- 历史搜索  -->
    <view class="history-box" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash-filled" size="17" @click="clearHistory"></uni-icons>
      </view>
      <view class="history-list">
        <uni-tag :text="item" v-for="(item,index) in historys" :key="index" @click="gotoGoodsList(item)"></uni-tag>
      </view>
    </view>

  </view>
</template>

<script>
  export default {
    data() {
      return {
        // 延迟器
        timer: null,
        // 搜索框的关键词
        kw: '',
        searchResult: [],

        // 历史检索数据
        historyList: []

      };
    },

    computed: {
      //  注意：由于数据是引用类型，所以不要直接基于原数据调用 reverse 方法，以免修改原数据中元素的顺序
      // 而是应该新建一个内存无关的数据，在进行反转
      historys() {
        return [...this.historyList].reverse()
      }
    },

    onLoad() {
      this.historyList = JSON.parse(uni.getStorageSync("kw") || '[]')
    },

    methods: {
      // 输入框输入监听
      input(e) {
        // 清除timer 对应的延时器
        clearTimeout(this.timer)
        // 重新启动一个延时器
        this.timer = setTimeout(() => {
          // 如果500毫秒内没有触发，则进行赋值
          this.kw = e
          this.handerDoSearch()
        }, 500);
      },
      async handerDoSearch() {
        if (this.kw === '') {
          this.searchResult = []
          return
        }
        const {
          data: res
        } =
        await uni.$http.get("/api/public/v1/goods/qsearch", {
          query: this.kw
        })
        if (res.meta.status !== 200) uni.$showMsg()
        this.searchResult = res.message
        this.saveSearchHistory()
      },
      gotoDetail(item) {
        uni.navigateTo({
          url: "/subpkg/goods_detail/goods_detail?good_id=" + item.goods_id
        })
      },

      // 存储搜索关键词，并去重
      saveSearchHistory() {
        const myset = new Set(this.historyList);
        myset.delete(this.kw)
        myset.add(this.kw)
        this.historyList = Array.from(myset)
        // 将数据存储到本地
        uni.setStorageSync("kw", JSON.stringify(this.historyList))
      },

      clearHistory() {
        uni.removeStorageSync("kw")
        this.historyList = []
      },
      gotoGoodsList(item){
        uni.navigateTo({
          url:"/subpkg/goods_list/goods_list?query="+item
        })
        
      }
    }
  }
</script>

<style lang="scss">
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 12px;
      padding: 13px 0;
      border-bottom: 1px solid #EFEFEF;

      .goods-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-right: 5px;

      }
    }
  }

  .history-box {
    padding: 0 5px;

    .history-title {
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;
      border-bottom: 1px solid #EFEFEF;
    }

    .history-list {
      margin-top: 5px;

      .uni-tag {
        margin-right: 5px;
      }
    }
  }
</style>